package com.right.health.app.ui.household;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.magic.basic.activity.BaseFragmentActivity;
import com.magic.basic.utils.CollectionUtil;
import com.magic.basic.utils.TimeUtil;
import com.magic.basic.utils.ToastUtil;
import com.magics.http.listener.OnHttpListener;
import com.magics.http.model.Request;
import com.magics.http.model.Response;
import com.right.health.app.R;
import com.right.health.app.base.BasePresenterFragment;
import com.right.health.app.bean.BloodPressureResponse;
import com.right.health.app.constants.AppConfig;
import com.right.health.app.net.HouseholdApi;
import com.right.health.app.ui.household.fragment.BloodPressureFragment1;
import com.right.health.app.ui.household.fragment.BloodPressureFragment2;
import com.right.health.app.ui.household.fragment.BloodPressureFragment3;
import com.right.health.app.widget.HealthSeekBar;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 * 血压
 * Created by hopeliao on 2019-10-10
 */
public class BloodPressureActivity extends BaseFragmentActivity implements View.OnClickListener, HealthSeekBar.OnSeekBarChangeListener, OnHttpListener {

    private static final int HTTP_CDOE_ADD = 1;
    private static final int HTTP_CDOE_LATEST = 2;
    public static final int HTTP_CDOE_TYPE_TYPE= 3;

    private HealthSeekBar mDiastolicSeekbar;

    private TextView mDiastolicValueTv;

    private HealthSeekBar mSystolicSeekbar;

    private TextView mSystolicValueTv;

    private HealthSeekBar mPulseSeekbar;

    private TextView mPulseValueTv;

    //舒张压
    private String mDiastolicValue;
    //收缩压
    private String mSystolicValue;
    // 脉搏
    private String mPulseValue;

    private HouseholdApi mHouseholdApi;

    private BloodPressureResponse.BloodPressureInfo mLatestInfo;

    private TextView mLatestTimeTv, mLatestPressureTv, mLatestPulseTv, mLatestStateTv;

    private TextView[] mLineTypeTvs;

    private Map<String, BasePresenterFragment> mConentFragments;

    private TextView mCurrTimeTv;

    @Override
    public void onCreate(Bundle bundle, String s) {
        setContentView(R.layout.blood_pressure_add);
    }

    @Override
    public void findView() {
        mCurrTimeTv = (TextView) findViewById(R.id.tv_curr_time);
        mLatestStateTv = (TextView) findViewById(R.id.tv_latest_state);
        mLatestPulseTv = (TextView) findViewById(R.id.tv_latest_pulse);
        mLatestPressureTv = (TextView) findViewById(R.id.tv_latest_pressure);
        mLatestTimeTv = (TextView) findViewById(R.id.tv_latest_time);

        mDiastolicSeekbar = (HealthSeekBar) findViewById(R.id.diastolic_seekbar);
        mDiastolicSeekbar.setTextIndex(60, 90);
        mDiastolicSeekbar.setOnSeekBarChangeListener(this);
        mDiastolicValueTv = (TextView) findViewById(R.id.tv_diastolic_value);

        mSystolicSeekbar = (HealthSeekBar) findViewById(R.id.systolic_seekbar);
        mSystolicSeekbar.setTextIndex(90, 140);
        mSystolicSeekbar.setOnSeekBarChangeListener(this);
        mSystolicValueTv = (TextView) findViewById(R.id.tv_systolic_value);

        mPulseSeekbar = (HealthSeekBar) findViewById(R.id.pulse_seekbar);
        mPulseSeekbar.setTextIndex(55, 100);
        mPulseSeekbar.setOnSeekBarChangeListener(this);
        mPulseValueTv = (TextView) findViewById(R.id.tv_pulse_value);

        findViewById(R.id.ib_list).setOnClickListener(this);
        findViewById(R.id.tv_save).setOnClickListener(this);

        mLineTypeTvs = new TextView[3];

        mLineTypeTvs[0] = findViewById(R.id.tv_today);
        mLineTypeTvs[1] = findViewById(R.id.tv_week);
        mLineTypeTvs[2] = findViewById(R.id.tv_month);

        for (TextView lineTypeTv : mLineTypeTvs) {
            lineTypeTv.setOnClickListener(mLineTypeClickListener);
        }

        mCurrTimeTv.setText(TimeUtil.convertTime(AppConfig.FORMAT_TIME, System.currentTimeMillis()));
    }

    private View.OnClickListener mLineTypeClickListener = this::replaceView;

    @Override
    public void initialize() {
        mConentFragments = new HashMap<>();

        mHouseholdApi = new HouseholdApi();
        mHouseholdApi.setListener(this);

        mHouseholdApi.addRequestCode(HTTP_CDOE_LATEST);
        mHouseholdApi.getLatestBloodPressure();

        replaceView(mLineTypeTvs[0]);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ib_list:
                startIntent(BloodPressureListActivity.class);
                break;
            case R.id.tv_save:
                send2Net();
                break;
        }
    }

    private void send2Net() {
        if (TextUtils.isEmpty(mDiastolicValue)) {
            ToastUtil.show(this, "请选择您的舒张压");
            return;
        }
        if (TextUtils.isEmpty(mSystolicValue)) {
            ToastUtil.show(this, "请选择您的收缩压");
            return;
        }
        if (TextUtils.isEmpty(mPulseValue)) {
            ToastUtil.show(this, "请选择您的脉搏");
            return;
        }
        mHouseholdApi.addRequestCode(HTTP_CDOE_ADD);
        mHouseholdApi.addBloodPressure(mSystolicValue, mDiastolicValue, mPulseValue);
    }

    private BasePresenterFragment mFragment;


    public synchronized void replaceView(View v) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (mFragment != null) {
            transaction.hide(mFragment);
        }

        for (TextView mLineTypeTv : mLineTypeTvs) {
            if (v == mLineTypeTv) {
                v.setSelected(true);
            } else {
                mLineTypeTv.setSelected(false);
            }
        }

        Class<? extends BasePresenterFragment> clazz = null;
        switch (v.getId()) {
            case R.id.tv_today:
                clazz = BloodPressureFragment1.class;
                break;
            case R.id.tv_week:
                clazz = BloodPressureFragment2.class;
                break;
            case R.id.tv_month:
                clazz = BloodPressureFragment3.class;
                break;
        }


        if(!mConentFragments.containsKey(String.valueOf(v.getId())) && clazz != null) {
            try {
                BasePresenterFragment fragment = clazz.newInstance();
                mConentFragments.put(String.valueOf(v.getId()), fragment);
                transaction.add(R.id.frameLayout, fragment);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }

        mFragment = mConentFragments.get(String.valueOf(v.getId()));

        assert mFragment != null;
        transaction.show(mFragment);
        transaction.commit();
    }

    @Override
    public void onProgressChanged(HealthSeekBar seekBar, float progress, boolean fromUser) {
        float value = seekBar.getMinValue() + progress * (seekBar.getMaxValue() - seekBar.getMinValue());
        float text = (float) (Math.round(value * 10)) / 10;
        if (seekBar == mDiastolicSeekbar) {
            mDiastolicValueTv.setText(String.valueOf(text));
            mDiastolicValue = String.valueOf(text);
        } else if (seekBar == mSystolicSeekbar) {
            mSystolicValueTv.setText(String.valueOf(text));
            mSystolicValue = String.valueOf(text);
        } else if (seekBar == mPulseSeekbar) {
            mPulseValueTv.setText(String.valueOf(text));
            mPulseValue = String.valueOf(text);
        }
    }

    private void refreshLatest() {
        if (mLatestInfo != null) {
            mLatestTimeTv.setText(mLatestInfo.createtime);
            mLatestPressureTv.setText(getString(R.string.format_blood_presure_value,mLatestInfo.highpressure,mLatestInfo.lowvoltage));
            mLatestPulseTv.setText(mLatestInfo.pulse+"次/分");
            mLatestInfo.refreshState(mLatestStateTv);
        }
    }

    private void refreshFragmentData() {
        List<Fragment>fragments=getSupportFragmentManager().getFragments();
        if (fragments != null) {
            for (Fragment fragment : fragments) {
                ((BasePresenterFragment)fragment).refreshData();
            }
        }
    }

    @Override
    public void onResponse(Request request, Response response) {
        if (response.isResponseFail()) {
            ToastUtil.show(this, response.error);
        } else {
            if (request.requestCode == HTTP_CDOE_ADD) {
                ToastUtil.show(this, "添加成功");
                mHouseholdApi.addRequestCode(HTTP_CDOE_LATEST);
                mHouseholdApi.getLatestBloodPressure();
                refreshFragmentData();
            } else if (request.requestCode == HTTP_CDOE_LATEST) {
                if (response.targetData instanceof BloodPressureResponse) {
                    BloodPressureResponse bloodPressureResponse = response.cast(BloodPressureResponse.class);

                    if (!CollectionUtil.isEmpty(bloodPressureResponse.bloodpressures)) {
                        mLatestInfo = bloodPressureResponse.bloodpressures.get(0);
                        refreshLatest();
                    }
                }
            }
        }
    }


}
